package com.micro.ai.auth.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.micro.ai.auth.dto.*;
import com.micro.ai.auth.service.UserService;
import com.micro.ai.commons.domain.ApiResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.micro.ai.auth.annotation.AuditLogAnnotation;
import java.util.List;

/**
 * 用户管理控制器
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/api/users")
@Tag(name = "用户管理", description = "用户注册、信息查询、密码修改、角色分配等操作")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 管理员创建用户
     */
    @PostMapping
    @PreAuthorize("hasAuthority('user:create')")
    @Operation(summary = "管理员创建用户", description = "管理员创建新用户（无需验证码，支持设置初始状态）")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "创建成功",
            content = @Content(schema = @Schema(implementation = UserDTO.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误或用户名已存在"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public ApiResponse<UserDTO> createUser(@Valid @RequestBody UserCreateRequest request) {
        log.info("管理员创建用户: tenantId={}, username={}", request.getTenantId(), request.getUsername());
        
        UserDTO user = userService.createUser(request);
        
        return ApiResponse.success("用户创建成功", user);
    }

    /**
     * 用户注册（公开接口）
     */
    @PostMapping("/register")
    @Operation(summary = "用户注册", description = "新用户注册（公开接口，需要验证码）")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "注册成功",
            content = @Content(schema = @Schema(implementation = UserDTO.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误或用户名已存在"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "租户不允许注册")
    })
    public ApiResponse<UserDTO> register(@Valid @RequestBody UserRegisterRequest request) {
        log.info("用户注册: tenantId={}, username={}", request.getTenantId(), request.getUsername());
        
        UserDTO user = userService.register(request);
        
        return ApiResponse.success("注册成功", user);
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/info")
    @Operation(summary = "获取当前用户", description = "获取当前登录用户的详细信息")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功",
            content = @Content(schema = @Schema(implementation = UserDTO.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "用户不存在")
    })
    public ApiResponse<UserDTO> getCurrentUser(@RequestAttribute("userId") String userId) {
        log.info("获取当前用户信息: userId={}", userId);
        
        UserDTO user = userService.getCurrentUser(userId);
        
        return ApiResponse.success("获取成功", user);
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/me")
    @Operation(summary = "更新个人信息", description = "更新当前登录用户的个人信息")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "更新成功",
            content = @Content(schema = @Schema(implementation = UserDTO.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权")
    })
    public ApiResponse<UserDTO> updateUser(@RequestAttribute("userId") String userId, 
                                          @Valid @RequestBody UserUpdateRequest request) {
        log.info("更新用户信息: userId={}", userId);
        
        UserDTO user = userService.updateUser(userId, request);
        
        return ApiResponse.success("更新成功", user);
    }

    /**
     * 修改密码
     */
    @PostMapping("/change-password")
    @Operation(summary = "修改密码", description = "修改当前用户的登录密码")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "修改成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误或原密码不正确"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权")
    })
    public ApiResponse<Void> changePassword(@RequestAttribute("userId") String userId,
                                           @Valid @RequestBody PasswordChangeRequest request) {
        log.info("修改密码: userId={}", userId);
        
        boolean success = userService.changePassword(userId, request);
        
        if (success) {
            return ApiResponse.successVoid("密码修改成功");
        } else {
            throw new RuntimeException("密码修改失败");
        }
    }

    /**
     * 重置密码
     */
    @PostMapping("/reset-password")
    @Operation(summary = "重置密码", description = "通过短信验证码重置密码")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "重置成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误或验证码错误"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "用户不存在")
    })
    public ApiResponse<Void> resetPassword(
            @Parameter(description = "手机号", required = true) @RequestParam("phone") String phone,
            @Parameter(description = "短信验证码", required = true) @RequestParam("smsCode") String smsCode,
            @Parameter(description = "新密码", required = true) @RequestParam("newPassword") String newPassword) {
        log.info("重置密码: phone={}", phone);
        
        boolean success = userService.resetPassword(phone, smsCode, newPassword);
        
        if (success) {
            return ApiResponse.successVoid("密码重置成功");
        } else {
            throw new RuntimeException("密码重置失败");
        }
    }

    /**
     * 为用户分配角色
     */
    @PostMapping("/{userId}/roles")
    @PreAuthorize("hasAuthority('user:assign-role')")
    @Operation(summary = "分配角色", description = "为用户分配一组角色（覆盖原有角色）")
    @AuditLogAnnotation(action = "UPDATE", resourceType = "USER", description = "分配用户角色")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "分配成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "用户或角色不存在")
    })
    public ApiResponse<Void> assignRoles(
            @Parameter(description = "用户ID", required = true) @PathVariable String userId,
            @Parameter(description = "角色ID列表", required = true) @RequestBody List<String> roleIds) {
        log.info("为用户分配角色: userId={}, roleIds={}", userId, roleIds);
        userService.assignRoles(userId, roleIds);
        return ApiResponse.successVoid("角色分配成功");
    }

    /**
     * 移除用户的角色
     */
    @DeleteMapping("/{userId}/roles")
    @PreAuthorize("hasAuthority('user:remove-role')")
    @Operation(summary = "移除角色", description = "移除用户的指定角色")
    @AuditLogAnnotation(action = "UPDATE", resourceType = "USER", description = "移除用户角色")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "移除成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "用户不存在")
    })
    public ApiResponse<Void> removeRoles(
            @Parameter(description = "用户ID", required = true) @PathVariable String userId,
            @Parameter(description = "角色ID列表", required = true) @RequestBody List<String> roleIds) {
        log.info("移除用户角色: userId={}, roleIds={}", userId, roleIds);
        userService.removeRoles(userId, roleIds);
        return ApiResponse.successVoid("角色移除成功");
    }

    /**
     * 分页查询用户（管理员）
     */
    @GetMapping("/all")
    @PreAuthorize("hasAuthority('user:view')")
    @Operation(summary = "分页查询用户", description = "根据条件分页查询用户列表（管理员）")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public ApiResponse<Page<UserDTO>> listUsers(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") int pageNum,
            @Parameter(description = "每页数量", example = "20") @RequestParam(defaultValue = "20") int pageSize,
            @Parameter(description = "租户ID") @RequestParam(required = false) String tenantId,
            @Parameter(description = "关键词（用户名/邮箱/手机号/昵称）") @RequestParam(required = false) String keyword,
            @Parameter(description = "状态") @RequestParam(required = false) String status) {
        Page<UserDTO> page = userService.listUsers(pageNum, pageSize, tenantId, keyword, status);
        return ApiResponse.success(page);
    }

    /**
     * 获取用户详情（管理员）
     */
    @GetMapping("/{userId}")
    @PreAuthorize("hasAuthority('user:view')")
    @Operation(summary = "获取用户详情", description = "根据用户ID获取用户详细信息（管理员）")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功",
            content = @Content(schema = @Schema(implementation = UserDTO.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "用户不存在")
    })
    public ApiResponse<UserDTO> getUserById(
            @Parameter(description = "用户ID", required = true) @PathVariable String userId) {
        UserDTO user = userService.getUserById(userId);
        return ApiResponse.success(user);
    }

    /**
     * 更新用户状态（管理员）
     */
    @PutMapping("/{userId}/status")
    @PreAuthorize("hasAuthority('user:manage')")
    @Operation(summary = "更新用户状态", description = "启用/禁用用户（管理员）")
    @AuditLogAnnotation(action = "UPDATE", resourceType = "USER", description = "更新用户状态")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "更新成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误或状态无效"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "用户不存在")
    })
    public ApiResponse<Void> updateUserStatus(
            @Parameter(description = "用户ID", required = true) @PathVariable String userId,
            @Parameter(description = "状态：active-活跃, inactive-未激活, locked-已锁定, suspended-已暂停", required = true, example = "active")
            @RequestParam String status) {
        log.info("更新用户状态: userId={}, status={}", userId, status);
        userService.updateUserStatus(userId, status);
        return ApiResponse.successVoid("用户状态更新成功");
    }

    /**
     * 删除用户（管理员）
     */
    @DeleteMapping("/{userId}")
    @PreAuthorize("hasAuthority('user:manage')")
    @Operation(summary = "删除用户", description = "删除指定用户（管理员）")
    @AuditLogAnnotation(action = "DELETE", resourceType = "USER", description = "删除用户")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "删除成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "用户不存在")
    })
    public ApiResponse<Void> deleteUser(
            @Parameter(description = "用户ID", required = true) @PathVariable String userId) {
        log.info("删除用户: userId={}", userId);
        userService.deleteUser(userId);
        return ApiResponse.successVoid("用户删除成功");
    }
}
